<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="button" value="点击" id="btn">
<h2>第<span id="num">0</span>次点击</h2>
<script>
    var btn = document.getElementById('btn');
    var num = document.getElementById('num');
    var l = window.location;
    (function(){
        var i = 0;
        btn.onclick =function(){
            i++;
            //可以自行定义的数据
            var data = {
                page:i
            }
           // var loc = location.href;

            //往loc中写信息，#p=1
            var loc = l.protocol+'//'+l.host+l.pathname+l.search+'#a'+i;


            //data 是一个对象
            //null 标题，在这不需要传入，因为浏览器基本不会采用它
            //loc 当前地址栏中的信息
            // pushState往历史记录里添加信息
            history.pushState(data,null,loc);

            num.innerHTML = i;
        }
        //操作location的前进或后退时会触发，浏览器的前进或后退
        window.onpopstate = function(e){
            var data = e.state; //从事件对象中获取 在 pushState中传入的对象数据，data
            var page = data.page;   //data.page
            num.innerHTML = page;
        }

        window.onload = function(){
            //通过链接打开页面
            var hash = l.hash;//#a1
            var page = hash.substr(2);  //从第2个字符开始到结束
            num.innerHTML = page;   //数字绑定到span
        }
    })()







    /*
     btn.onclick = function(){
     i++;
     var myObj = {page:i}

     history.pushState(myObj,null)
     num.innerHTML = i;

     }

     window.onpopstate = function(e){
     var data = e.state;
     num.innerHTML = data.page;
     }
     */
</script>
</body>
</html>